/**
 * Yutou弹框
 * 调用方法：
 */

import * as React from 'react';
import { View, Text, TextStyle } from 'react-native';
import AliyunOSS from 'aliyun-oss-react-native';
import RNFS from 'react-native-fs';
import moment from 'moment';

import Button from '../../../../../../components/Button';
import styles from './style';
import FastImage from '../../../../../../components/FastImage';
import { sendLogAlert } from '../../../../../../constant/resource';
import { modalClose, toolTipOpen } from '../../../../../../util/global';
import { AppApi } from '../../../../../../api';
import { isIOS } from '../../../../../../constant';

export const sendFrontLog = async (needAlert = true): Promise<void> => {
  const res = await AppApi.getFrontLogSTSToken();

  if (res.code !== 0) {
    return;
  }

  const { ossPath, ossSTS } = res.data;
  const { accessKeyId, accessKeySecret, stsToken, endPoint, bucket } = ossSTS;

  AliyunOSS.initWithSecurityToken(
    stsToken,
    accessKeyId,
    accessKeySecret,
    endPoint
  );

  const logPath = isIOS
    ? `${RNFS.DocumentDirectoryPath}/log`
    : '/storage/emulated/0/com.mifengxiaoban.studygroup/log';

  const agoraLogPath = isIOS
    ? `${RNFS.LibraryDirectoryPath}/Caches`
    : '/storage/emulated/0/Android/data/com.mifengxiaoban.studygroup/files';

  const readDirRes = await RNFS.readDir(logPath);
  const readAgoraDirRes = await RNFS.readDir(agoraLogPath);

  const logFilenames: string[] = [];
  const agoraLogFileNames: string[] = [];

  readDirRes.forEach(({ name }): void => {
    const nameArray = name.split('_');

    if (nameArray.length > 1) {
      const fileDate = nameArray[1];
      const fromNow = moment(fileDate, 'YYYYMMDD').fromNow();
      if (fromNow.includes('hours')) {
        logFilenames.push(name);
      } else if (fromNow.includes('days')) {
        const fromNowDays = fromNow.split(' ')[0]
          ? Number(fromNow.split(' ')[0])
          : 0;
        if (fromNowDays <= 7) {
          logFilenames.push(name);
        }
      }
    }
  });

  readAgoraDirRes.forEach(({ name }): void => {
    if (name.includes('agora')) {
      agoraLogFileNames.push(name);
    }
  });

  let logCount = 0;
  const logNum = logFilenames.length + agoraLogFileNames.length;

  const checkSendLogDone = (): void => {
    if (logCount === logNum) {
      toolTipOpen({ desc: '线索已发送' });
    }
  };

  const sendLogFail = (): void => {
    toolTipOpen({ desc: '线索发送失败' });
  };

  logFilenames.forEach((name): void => {
    AliyunOSS.asyncUpload(
      bucket,
      `${ossPath}/${name}`,
      `file://${logPath}/${name}`
    )
      .then((): void => {
        logCount += 1;
        if (needAlert) {
          checkSendLogDone();
        }
      })
      .catch((): void => {
        if (needAlert) {
          sendLogFail();
        }
      });
  });

  agoraLogFileNames.forEach((name): void => {
    AliyunOSS.asyncUpload(
      bucket,
      `${ossPath}/${name}`,
      `file://${agoraLogPath}/${name}`
    )
      .then((): void => {
        logCount += 1;
        if (needAlert) {
          checkSendLogDone();
        }
      })
      .catch((): void => {
        if (needAlert) {
          sendLogFail();
        }
      });
  });
};

const SendLogAlert = (): React.ReactElement => {
  return (
    <FastImage source={sendLogAlert} style={styles.container}>
      <View style={styles.loadDesc}>
        <Text style={styles.desc}>
          为了提供流畅的上课体验，点击发送调试线索，即可让工程师获得服务改善机会，谢谢你的参与！
        </Text>
      </View>
      <View style={styles.loadButtons}>
        <Button
          style={styles.sure}
          text="点击发送线索"
          textStyle={styles.sureDesc}
          onPress={(): void => {
            sendFrontLog();
            modalClose();
          }}
        />
        <Button
          style={styles.cancel}
          text="路过逛逛"
          textStyle={styles.cancelDesc}
          onPress={modalClose}
        />
      </View>
    </FastImage>
  );
};

export default SendLogAlert;
